package com.donger.business.upms.handler.login;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.business.upms.enums.LoginTypeEnum;
import com.donger.business.upms.entity.SysSocialDetails;
import com.donger.business.upms.entity.SysUser;
import com.donger.business.upms.mapper.SysSocialDetailsMapper;
import com.donger.business.upms.service.ISysUserService;
import com.donger.common.core.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author lengleng
 * @date 2018/11/18
 */
@Slf4j
@Component("WEWORK")
@AllArgsConstructor
public class WeworkLoginHandler extends AbstractLoginHandler {
    private final ISysUserService sysUserService;
    private final SysSocialDetailsMapper sysSocialDetailsMapper;

    /**
     * 微信登录传入code
     * <p>
     * 通过code 调用qq 获取唯一标识
     *
     * @param code
     * @return
     */
    @Override
    public String identify(String code) {
        SysSocialDetails condition = new SysSocialDetails();
        condition.setType(LoginTypeEnum.WEWORK.getType());

        SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));

        // 获取登录用户所需要的token
        String tokenUrl = String.format(SecurityConstants.WEWORK_AUTHORIZATION_TOKEN
                , socialDetails.getAppId(), socialDetails.getAppSecret());
        String tokenResult = HttpUtil.get(tokenUrl);
        log.debug("企业微信获取token报文:{}", tokenResult);

        Object tmp = JSONUtil.parseObj(tokenResult).get("access_token");

        String userUrl = String.format(SecurityConstants.WEWORK_AUTHORIZATION_USERID
                , tmp.toString(), code);
        String result = HttpUtil.get(userUrl);
        log.debug("企业微信获取用户信息报文 -> {}", result);
        Object obj = JSONUtil.parseObj(result).get("UserId");
        return obj.toString();
    }

    /**
     * openId 获取用户信息
     *
     * @param openId
     * @return
     */
    @Override
    public SysUser info(String openId) {
        SysUser user = sysUserService
                .getOne(Wrappers.<SysUser>query()
                        .lambda().eq(SysUser::getWework, openId));

        if (user == null) {
            log.info("企业微信未绑定:{}", openId);
            return null;
        }
        return user;
    }
}
